﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore.Storage;
using News.Models.Database;
using System.Linq;
using News.Models;
using System.Security.Cryptography.X509Certificates;

namespace News.Controllers
{
	/// <summary>
	/// Home控制器
	/// </summary>
	/// 定义路由

	[Route("/[action].html")]
	[Route("[controller]/[action]")]
	public class HomeController : Controller
	{
		private readonly NewsContext _newsContext;
		public HomeController(NewsContext newsContext)
		{
			_newsContext = newsContext;
		}

		//使用数据库查询
		//1、查询数据 条件查询 var list = _newsContext.表名.Where().Tolist();
		//2、把list传递到页面上		ViewData ViewBag ViewModel

		/// <summary>
		/// 控制器方法
		/// 添加路由实现 url/index.html   /Home/index
		/// </summary>
		/// <returns></returns>
		/// 首页方法
		/// 省略控制器名Home 方法名(Index).html
		[Route("/index.html")]
		[Route("/")]
		public IActionResult Index(int cateId, int page, string search_con)
		{
			//1、查询 分类数据
			//			数据库上下文. 数据库表. 所有分类结果
			var cates = _newsContext.Categories.ToList();
			//3 默认全部新闻展开
			var news = _newsContext.NewsPosts.ToList();

			if (cateId == 0)
			{
				//取cateId为第一个分类Id
				cateId = cates.FirstOrDefault().CateId;
				news = _newsContext.NewsPosts.ToList();
			}
			else
			{
				//新闻的Id绑定到新闻分类的Id，可以检索新闻分类查找新闻
				news = _newsContext.NewsPosts.Where(x => x.CateId == cateId).ToList();
			}
			//判断分页
			if (page == 0)
			{
				page = 1;
			}
			if (search_con != null)
			{
				news = _newsContext.NewsPosts.Where(x => x.Title.Contains(search_con)).ToList();
			}
			//页码
			ViewData["page"] = page;
			//分类列表
			//2、传递	分类数据
			//		参数名字
			ViewData["Cates"] = cates;
			//分类Id
			ViewData["cateId"] = cateId;
			//将变量cateId的值赋给ViewData
			Public.now_cateId = cateId;
			ViewData["NewsPosts"] = news;
			return View();
		}
		public IActionResult Search(Search_Con sea_Con)
		{
			var search_con = _newsContext.NewsPosts.Where(x => x.Title.Contains(sea_Con.Sea_Content)).ToList();
			if (search_con == null)
				return Content("Error");
			else
			{
				ViewData["NewsPosts"] = search_con;
				return Content("ok");
			}
		}
		public IActionResult Detail(int newsID)
		{
			Public.now_newsId = newsID;
			
			return View();
		}
	}
}
